# -*- coding: utf-8 -*-


import random, time, datetime
import dbwrapper
from dbwrapper.companyx.login_session import LoginSession
from service.public.login_service import LoginService
from helper.login_session_manager import LoginSessionManager

from service.public.applyshenghe import Applyshenghe
from service.public.cdkey_service import CdkeyService
from cgi import parse
from service.webside.shop_config_service import ShopConfigService
from service.webside.company_management_service import CompanyManagementService
from service.webside.company_service import CompanyService
from service.webside.company_servicereport import Companyservicereport
from service.clientside.order_service import OrderService

from common.debug import Debug
import cStringIO,cgi
import urllib2
import json

def application(environ, start_response):
    '''
    目录规划：
    
    web目录：http://xx//poscloud/v1/module/submodule/...    
    ROOT /poscloud/v1

    模块：
    ROOT/company/login - 登录操作
    ROOT/company/shop - 分店相关信息操作
    ROOT/company/shop_group - 分店群组操作
    ROOT/company/user - 用户信息维护
    ROOT/company/user_rights - 用户权限维护
    ROOT/shop/config/get - 获取分店业务信息
    ROOT/shop/config/set - 设置分店业务信息
    ROOT/shop/order - 分店订单信息维护
    
    environ['PATH_INFO']包含 ROOT 后面的目录
    '''
    debug=Debug()
    if environ['PATH_INFO'] == None:
        response_paramsARRAY=[]
        response_params={}
        response_params['ret'] =-1
        response_params['msg'] = 'bad request'
        response_paramsARRAY = []
        strtemp=json.dumps(response_params)
        response_paramsARRAY.append(strtemp)        
        return say_bad(start_response,-1,"bad request")
    
      
    paths = str(environ['PATH_INFO'])[1:].split('/')

    #从environ里面解析出http参数来
    #params = parse(None, environ)
    
    method = environ['REQUEST_METHOD'].upper()
    if method == 'GET':
        params = cgi.FieldStorage(environ=environ)     
    else:
        postdata = environ['wsgi.input'].read(int(environ.get('CONTENT_LENGTH', '0')))
        params = cgi.FieldStorage(fp = cStringIO.StringIO(postdata), environ = environ)

        #用unquote 将POST数据 解码 前端用JS 的escape 编码
        for key in params.keys():
            if params[key].value.find('%u') >= 0:
                params[key].value=urllib2.unquote(params[key].value.replace('%u', '\\u').decode('unicode_escape')).encode('utf-8')
            elif key == 'binary':
                continue
            else:
                params[key].value =urllib2.unquote(params[key].value).decode('unicode_escape')
                 
    if len(paths) > 0:  
        if paths[0] == 'company':   
            return company_application(params, start_response, paths)
        elif paths[0] == "shop":
            return shop_application(params, start_response, paths)
        elif paths[0] == "companymanagement":
            return company_management_application(params, start_response, paths)
        elif paths[0] == "apply":
            return apply_application(params, start_response, paths)
        else:
            return say_bad(start_response,-1,"unknow path")
    else:
        return say_bad(start_response,-1,"invalid path")


def say_bad(start_response,code,msg): 
    response_params={}
    response_params['ret'] =code
    response_params['msg'] = msg
    response_params['data'] =''    
    strtemp=json.dumps(response_params)
    status = '200 ok'
    output = strtemp    
    response_headers = [('Content-type', 'text/plain'),
                ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    
    return [output]     


def company_application(params, start_response, paths): 
    '''
       公司层面的接口
    '''
    if len(paths) < 2:
        return say_bad(start_response,-1, 'invalid pathdd')

    if paths[1] == 'login':
        loginService = LoginService(start_response)
        return loginService.application(params)
    #cdkey激活
    elif paths[1] == 'cdkey':
        cdkeyservice=CdkeyService(start_response)
        return cdkeyservice.application(params)     
    elif paths[1] == 'get' or  paths[1] == 'sh' or paths[1] == 'shopsh' :
        loginService = LoginService(start_response)
        return loginService.applicationget(params,paths)
    #公司信息，基本权限，区域信息 
    elif paths[1] == 'config':
        companyservice=CompanyService(start_response)
        return companyservice.application(params, paths)           
    elif paths[1] == 'report':
        companyservicereport=Companyservicereport(start_response)
        return companyservicereport.application(params, paths)           
               
               
    return say_bad(start_response,-1, "invalid pathdd")


def company_management_application(params, start_response, paths):
    '''
       总库层面的接口
    '''
    if len(paths) < 3:
        return say_bad(start_response,-1,"invalid path")

    companymanagementservice = CompanyManagementService(start_response)
    if paths[1] == 'config':
        return companymanagementservice.application(params, paths)    
    else:
        return say_bad(start_response,-1, "invalid path")
    
    return say_bad(start_response,-1,"invalid path")



def shop_application(params, start_response, paths):
    '''
    分店层面的接口
    '''
    if len(paths) < 2:
        return say_bad(start_response,-1,"invalid path")
    
    if paths[1] == 'config':    
        shopConfigService = ShopConfigService(start_response)
        return shopConfigService.application(params, paths)
    elif paths[1] == 'order':
        orderService = OrderService(start_response)
        return orderService.application(params)
    else:
        return say_bad(start_response,-1,"invalid path")


def apply_application(params, start_response, paths): 
    '''
        申请艾云服务
    '''
    if len(paths) < 2:
        return say_bad(start_response,-1,"invalid path")

    if paths[1] == 'sub':
        loginService = LoginService(start_response)
        return loginService.applysub(params)
    elif paths[1] == 'shenghe':
        applyshenghe=Applyshenghe(start_response)
        return applyshenghe.applysub(params)
    elif paths[1]=='shopshenghe':
        applyshenghe=Applyshenghe(start_response)
        return applyshenghe.webapplyshop(params)
        
    return say_bad(start_response,-1, "invalid path")
